﻿/*
#------------------------------------------------------------------------------
#-- Program Name:	[dbo].[fnBkp_HasFullBackup]
#-- Purpose:		Checks for a valid full backup of a database
#--	Last Update:	04/14/2014
#--					For a complete history - please review comments in Version
#--					Control.
#-- Called By:		[dbo].[spBkp_Differential]
#------------------------------------------------------------------------------
*/
CREATE FUNCTION [dbo].[fnBkp_HasFullBackup]
(
	@database_name		sysname
)
RETURNS BIT
AS
  BEGIN
	--- Declare Local Variables
	DECLARE	@HasFullBkp bit
	
	--- Initialize Local Variables
	SET		@HasFullBkp = 1

	--- A record will exist to this query if a full backup is needed
	IF EXISTS (
		SELECT		TOP 1
					db.[name] [database_name],
					db.[recovery_model_desc],
					bs.[database_name]
		FROM		[sys].[database_recovery_status] drs
		JOIN		[sys].[databases] db ON drs.[database_id] = db.[database_id]
		LEFT JOIN	[msdb].[dbo].[backupset] bs ON db.[name] = bs.[database_name]
					AND drs.[family_guid] = bs.[family_guid]
					AND drs.[database_guid] = bs.[database_guid]
		WHERE		bs.[family_guid] IS NULL
					AND db.[name] = @database_name
		)
		SET		@HasFullBkp = 0

	--- Return the Answer to the Question
	RETURN	@HasFullBkp
  END
